// 导入数据库API
const db = require('../../config/db');
// 导入加密/解密文件
const aes2 = require('../../utils/aes2');
// 导入jwt token工具
const JwtUtil = require('../../utils/jwt');
// 封装注册接口
const register = (user_id, user_acc, user_pwd, user_name, user_create_time) => {
    return new Promise((resolve, reject) => {
        let user_check_sql = `select * from db_user where user_acc = "${user_acc}"`
        db.query(user_check_sql, (error, result) => {
            if (error) {
                reject({
                    code: -1,
                    msg: '查询用户异常。'
                })
            } else {
                // result: 数组
                // result.length == 0 该账号还没被注册
                // console.log("4.0",{user_id, user_acc, user_pwd, user_name, user_create_time});
                if (result.length == 0) {
                    let pwd = aes2.aesEncrypt(user_pwd)//加密
                    let role = 'consumer';
                    let user_insert_sql = `insert into db_user(user_id,user_acc,user_pwd,user_name,user_create_time,role) values("${user_id}","${user_acc}","${pwd}","${user_name}","${user_create_time}","${role}")`;
                    db.query(user_insert_sql, (err, rows) => {
                        if (err) {
                            reject({
                                code: -1,
                                msg: '用户注册失败。',
                                err
                            })
                        } else {
                            resolve({
                                code: 200,
                                msg: `用户${user_acc}注册成功。`,
                                user_name
                            })
                        }
                    })
                } else {
                    resolve({
                        code: 201,
                        msg: '该账号已经存在。'
                    })
                }
            }
        })
    })
}

// 封装用户登录接口
// 设置用户登录的有效时间
// 把用户的user_id生产临时的随机字符串(token)
// token: 临时身份（令牌）
const login = (user_acc, user_pwd) => {
    return new Promise((resolve, reject) => {
        // 查询用户表sql语句
        let user_check_sql = `select * from db_user where user_acc="${user_acc}"`;
        db.query(user_check_sql, (err, rows) => {
            if (err) {
                resolve({
                    code: -1,
                    msg: '账号或密码错误。'
                })
            } else {
                if (rows.length == 1) {
                    // 匹配密码
                    // 参数1：前端提交的密码，参数2：数据库的密码
                    // console.log('7.0', aes2.aesDecrypt(user_pwd, rows[0]['user_pwd']));
                    if (aes2.aesDecrypt(user_pwd, rows[0]['user_pwd'])) {
                        let [{ user_id, user_name, user_acc, user_phone }] = rows;
                        // 将用户id传入并生成token
                        let jwt = new JwtUtil(user_id);
                        // 获取token
                        let token = jwt.generateToken();
                        // 定义用户对象
                        let user = {
                            code: 200,
                            msg: `用户${user_acc},登录成功。`,
                            token,
                            user_name,
                            user_acc,
                            // user_avator
                        }
                        if (user_phone) {
                            user['user_phone'] = user_phone
                        }
                        // 将 token 等信息反馈给客户端
                        resolve(user);
                    } else {
                        resolve({
                            code: -1,
                            msg: '账号或密码错误1'
                        })
                    }
                }
                else if (rows.length == 0) {
                    resolve({
                        code: -1,
                        msg: '账号不存在。'
                    })
                }
                else {
                    resolve({
                        code: 500,
                        msg: '系统异常。'
                    })
                }
            }
        })
    })
}

// 操作数据库的业务
module.exports = {
    // 示例：
    test() {
        return new Promise((resolve, reject) => { })
    },
    // 注册接口
    register(user_id, user_acc, user_pwd, user_name, user_create_time) {
        // To do ....
        return register(user_id, user_acc, user_pwd, user_name, user_create_time);
    },
    // 登录接口
    login(user_acc, user_pwd) {
        // To do ....
        return login(user_acc, user_pwd);
    },

    modify(user_id, user_name, user_pwd) {
        return new Promise((resolve, reject) => {
            let modify_info_sql = ''
            if (user_name.length != 0) {
                modify_info_sql = `update db_user set user_name= "${user_name}" where  user_id= "${user_id}"`;
                // console.log('1.0', {modify_info_sql})
                if (user_pwd.length != 0) {
                    modify_info_sql = `update db_user set user_name= "${user_name}",user_pwd="${user_pwd}" where  user_id= "${user_id}"`;
                    // console.log('2.0', { modify_info_sql })
                }
            }
            db.query(modify_info_sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "修改用户资料失败。",
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "修改用户资料成功。"
                    })
                }
            })
        })
    },

    // 删除用户信息
    remove(user_id) {
        return new Promise((resolve, reject) => {
            let sql = `delete from  db_user where user_id = "${user_id}"`
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "删除用户失败。",
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "删除用户成功。"
                    })
                }
            })
        })
    },

    // 获取用户信息
    get_userInfo(user_id) {
        return new Promise((resolve, reject) => {
            let sql = `select user_name,user_acc from db_user where user_id = "${user_id}"`;
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: '获取用户信息失败。'
                    })
                } else {
                    reject({
                        code: 200,
                        msg: '获取用户信息成功。',
                        data: rows
                    })
                }
            })
        })
    },

}